package com.lebang.component;

import com.lebang.entity.LbbAppLog;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.buss.RecordMsg;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberNotice;
import com.lebang.entity.member.LbbMemberRecord;
import com.lebang.entity.sys.SdkUploadPackage;
import com.lebang.mapper.BlackPkgMapper;
import com.lebang.mapper.LbbMemberNoticeMapper;
import com.lebang.mapper.MemberCashWithdrawalMapper;
import com.lebang.mapper.sys.SdkUploadPackageMapper;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.NoticeType;
import com.lebang.service.buss.MemberService;
import com.lebang.service.mongodb.IAppLogMongodb;
import com.lebang.service.sys.PkgBlackLogService;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Component
@Slf4j
public class AsyncsComponent {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SdkUploadPackageMapper sdk;
    @Autowired
    private LbbMemberNoticeMapper lbbMemberNoticeMapper;
    @Autowired
    private SendComponent sendComponent;
    @Autowired
    private UMengPushComponent uMengPushComponent;
    @Autowired
    private BlackPkgMapper blackPkgMapper;

    @Autowired
    private PkgBlackLogService pkgBlackLogService;

    @Autowired
    private MemberCashWithdrawalMapper memberCashWithdrawalMapper;





    /**
     * 新发布任务时通知活跃用户
     *
     * @param taskname
     * @param taskid
     */
    @Async
    public void recordToMember(String taskname, String taskid) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime start = now.minusDays(30);
            List<String> members = memberCashWithdrawalMapper.selectMemberIdByCash(start,now);
            List<RecordMsg> recordMsgList = new ArrayList<>();
            List<List<String>> sprateList = ListUtils.partition(members, 500);
            List<String> pushList = new ArrayList<>();
            sprateList.forEach(s -> pushList.add(String.join(",", s)));
            for (String member : pushList) {
                RecordMsg recordMsg = new RecordMsg();
                recordMsg.setMemberId(member);
                recordMsg.setTitle("新任务上架通知");
                recordMsg.setMsg("新任务" + taskname + "上架了,赶紧来做任务吧!");
                recordMsgList.add(recordMsg);
            }
            sendComponent.addToEventToQueue(recordMsgList);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Async
    /**
     * 获取用户手机安装软件包名
     * **/
    public void uploadPackage(RequestHeaders requestHeaders, String str) {
        if (TextUtil.isEmpty(str)) {
            return;
        }
        String imei = requestHeaders.getImei();
        if (TextUtil.isEmpty(imei)) {
            return;
        }
        String key = UUIDUtil.M();
        List<String> blackList=blackPkgMapper.selectAll();
        boolean i = redisClient.tryGetDistributedLock("lock:imei:" + imei, key, 86400000);
        try {
            if (i) {
                String memberId = requestHeaders.getUserid();
                String appStore = requestHeaders.getAppStore();
                String os = requestHeaders.getOs();
                String osv = requestHeaders.getOsv();
                List<String> stringList = Arrays.asList(str.split(","));
                stringList.forEach(s->{
                    if (blackList.contains(s)) {
                        pkgBlackLogService.addLog(s, requestHeaders, "安装了违禁的包:{ " + s + " }");
                    }
                });
                List<String> newPkgList=new ArrayList<>(stringList);
                List<String> checkList = sdk.checkList(imei);
                //装过的不在写入
                newPkgList.removeAll(checkList);
                List<SdkUploadPackage> list = new ArrayList<>(1);
                newPkgList.forEach(s -> {
                    SdkUploadPackage sd = new SdkUploadPackage();
                    sd.setPackageName(s);
                    sd.setAppstore(appStore);
                    sd.setMemberId(memberId);
                    sd.setImei(imei);
                    sd.setOs(os);
                    sd.setOsv(osv);
                    sd.setCreateTime(new java.util.Date());
                    sd.setModifyTime(new java.util.Date());
                    list.add(sd);
                });
                if (list.size() > 0) {
                    sdk.piplineInsert(list);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
          //  redisClient.releaseDistributedLock("lock:imei:" + imei, key);
        }
    }


    /**
     * 写入，发送通知
     *
     * @param record
     * @param desc
     * @author weizx
     * @date 2018年7月27日 下午2:41:35
     */
    @Async
    public void notice(LbbMemberRecord record, String title, String desc) {

        LbbMember member = memberService.getMemberByMemberId(record.getMemberId());
        if (member == null) {
            return;
        }
        try {
            uMengPushComponent.sendAndroidCustomizedcast(title, desc, member.getMemberId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        member.setNoticeCount(member.getNoticeCount() + 1);
        memberService.updateMemberById(member);
        LbbMemberNotice notice = new LbbMemberNotice();
        notice.setAppId(record.getAppId());
        notice.setAppStore(record.getAppStore());
        notice.setCategory(NoticeType.Text);
        notice.setContent("");
        notice.setMemberId(record.getMemberId());
        notice.setStatus("On");
        notice.setSubtitle(desc);
        notice.setTitle(title);
        notice.setHasDeleted(Booleans.False.name());
        notice.setCreateTime(new java.util.Date());
        lbbMemberNoticeMapper.insertSelective(notice);

    }

    /**
     * 写入，发送通知
     *
     * @param memberId
     * @param desc
     * @author weizx
     * @date 2018年7月27日 下午2:41:35
     */
    @Async
    public void sendNotice(String memberId, String title, String desc) {
        LbbMember member = memberService.getMemberByMemberId(memberId);
        if (member == null) {
            return;
        }
        try {
            uMengPushComponent.sendAndroidCustomizedcast(title, desc, member.getMemberId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        member.setNoticeCount(member.getNoticeCount() + 1);
        memberService.updateMemberById(member);
        LbbMemberNotice notice = new LbbMemberNotice();
        notice.setAppId("xianyu");
        notice.setAppStore("");
        notice.setCategory(NoticeType.Text);
        notice.setContent("");
        notice.setMemberId(memberId);
        notice.setStatus("On");
        notice.setSubtitle(desc);
        notice.setTitle(title);
        notice.setHasDeleted(Booleans.False.name());
        notice.setCreateTime(new java.util.Date());
        lbbMemberNoticeMapper.insertSelective(notice);

    }
    private static final DateTimeFormatter da= DateTimeFormatter.ofPattern("yyyyMMdd");
//    @Autowired
//    private KafkaTemplate<String, String> kafkaTemplate;
    /**
     * 添加日志
     * <p>
     * customHttpHeader 自定义的头信息
     */
    @Autowired
    private  IAppLogMongodb appLogMongodb;

    public void addLog(RequestHeaders customHttpHeader) {
        try {
            LbbAppLog log = new LbbAppLog();
            log.setAppId(customHttpHeader.getAppid());
            log.setAppStore(customHttpHeader.getAppStore());
            log.setVersion(customHttpHeader.getVersion());
            log.setImei(customHttpHeader.getImei());
            log.setBrand(customHttpHeader.getBrand());
            log.setOs(customHttpHeader.getOs());
            log.setOsv(customHttpHeader.getOsv());
            log.setLat(customHttpHeader.getLat());
            log.setLng(customHttpHeader.getLng());
            log.setIpAddr(customHttpHeader.getIpAddr());
            log.setMacAddr(customHttpHeader.getMacAddr());
            log.setSessionId(customHttpHeader.getSessionId());
            log.setReq(customHttpHeader.getServletPath());
            log.setParams(customHttpHeader.getParams());
            log.setMemberId(customHttpHeader.getUserid());
            log.setHasDeleted(Booleans.False.name());
            log.setCreateTime(LocalDateTime.now());
            appLogMongodb.save(log);
           // kafkaTemplate.send("req_log", JSON.toJSONString(log));
        }catch (Exception e){
         log.error("日志写入失败!");
        }

    }


}
